package com.glorious.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.glorious.dto.response.appuser.AppUserAuthResponse;
import com.glorious.entities.AppUser;
import com.glorious.exception.NormalException;
import com.glorious.mapper.AppUserMapper;
import com.glorious.service.IAppUserService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class AppUserServiceImpl extends ServiceImpl<AppUserMapper, AppUser> implements IAppUserService {

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Long add(AppUser appUser) {
        boolean save = super.save(appUser);
        if (!save) {
            throw new NormalException("添加用户失败");
        }
        return 1L;
    }

    @Override
    public AppUserAuthResponse getByOpenId(String openId) {
        AppUser appUser = super.getOne(Wrappers.<AppUser>lambdaQuery().eq(AppUser::getOpenId, openId).last("LIMIT 1"));
        AppUserAuthResponse response = null;
        if (ObjectUtil.isNotNull(appUser)) {
            response = new AppUserAuthResponse();
            BeanUtil.copyProperties(appUser, response);
            response.setUserId(appUser.getId());
        }
        return response;
    }

    @Override
    public AppUserAuthResponse getByMobile(String mobile) {
        AppUser appUser = super.getOne(Wrappers.<AppUser>lambdaQuery().eq(AppUser::getMobile, mobile).last("LIMIT 1"));
        AppUserAuthResponse response = null;
        if (ObjectUtil.isNotNull(appUser)) {
            response = new AppUserAuthResponse();
            BeanUtil.copyProperties(appUser, response);
            response.setUserId(appUser.getId());
        }
        return response;
    }
}
